from rest_framework import serializers
from app01 import models


class PublisherModelSerializer(serializers.ModelSerializer):
	class Meta:
		model = models.Publisher
		fields = '__all__'


class AuthorModelSerializer(serializers.ModelSerializer):
	class Meta:
		model = models.Author
		fields = '__all__'


class BookModelSerializer(serializers.ModelSerializer):
	category_info = serializers.SerializerMethodField()  # 执行 get_字段名的方法
	publisher_info = serializers.SerializerMethodField()  #
	authors_info = serializers.SerializerMethodField()  #

	def get_category_info(self, obj):
		return obj.get_category_display()

	def get_publisher_info(self, obj):
		return PublisherModelSerializer(obj.publisher).data

	def get_authors_info(self, obj):
		return AuthorModelSerializer(obj.authors.all(), many=True).data

	class Meta:
		model = models.Book
		fields = '__all__'
		extra_kwargs = {
			'category': {'write_only': True},
			'publisher': {'write_only': True, },
			'authors': {'write_only': True, 'required': False}
		}
